package com.example.demo.config;

import com.example.demo.utils.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.RequestParameterBuilder;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.schema.ScalarType;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ParameterType;
import springfox.documentation.service.RequestParameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.ArrayList;
import java.util.List;

@EnableOpenApi
@Configuration
public class SwaggerConfig {
    @Value("${swaggerhost:}")
    private String swaggerhost;

    @Value("${swaggerenable:true}")
    private Boolean swaggerenable;

    @Bean
    public Docket createRestApi() {
        List<RequestParameter> pars = new ArrayList<>();
        RequestParameterBuilder ticketPar = new RequestParameterBuilder();
        ticketPar.name("access_token").description("请求token")
                .in(ParameterType.HEADER)
                .query(q->q.model(m -> m.scalarModel(ScalarType.STRING)))
                .required(false);
        pars.add(ticketPar.build());
        if (StringUtils.isNotEmpty(swaggerhost)) {
            return new Docket(DocumentationType.SWAGGER_2)
                    .host(swaggerhost)
                    .enable(swaggerenable)
                    .apiInfo(apiInfo())
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
                    .paths(PathSelectors.any())
                    .build().globalRequestParameters(pars);
        } else {
            return new Docket(DocumentationType.SWAGGER_2)
                    .enable(swaggerenable)
                    .apiInfo(apiInfo())
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
                    .paths(PathSelectors.any())
                    .build().globalRequestParameters(pars);
        }

    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("springboot-demo")
                .description("springboot-demo api接口文档")
                .termsOfServiceUrl("http://www.springboot-demo.cn/")
                .version("1.0")
                .build();
    }
}
